package com.ltkj.baseplatform.service.impl;

import java.util.List;

import com.ltkj.baseplatform.domain.WuserExt;
import com.ltkj.baseplatform.domain.req.WuserPartnerAddReq;
import com.ltkj.baseplatform.mapper.WuserExtMapper;
import com.ltkj.baseplatform.service.IsendMessage;
import com.ltkj.baseplatform.util.EidUtil;
import com.ltkj.baseplatform.util.IdCardUtil;
import com.ltkj.common.core.utils.StringUtils;
import com.ltkj.common.core.utils.bean.BeanUtils;
import com.ltkj.common.core.web.domain.AjaxResult;
import com.ltkj.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ltkj.baseplatform.mapper.WuserPartnerMapper;
import com.ltkj.baseplatform.domain.WuserPartner;
import com.ltkj.baseplatform.service.IWuserPartnerService;

/**
 * 游客信息Service业务层处理
 * 
 * @author xupf
 * @date 2023-10-10
 */
@Service
public class WuserPartnerServiceImpl implements IWuserPartnerService 
{
    @Autowired
    private WuserPartnerMapper wuserPartnerMapper;
    @Autowired
    private WuserExtMapper wuserExtMapper;
    @Autowired
    private IsendMessage sendMessage;
    /**
     * 身份证验证相关
     */
    @Value("${tx.secretId}")
    private String secretId;
    @Value("${tx.secretKey}")
    private String secretKey;
    @Value("${tx.merchantId}")
    private String merchantId;
    @Value("${tx.motion.merchantId}")
    private String motionMerchantId;

    /**
     * 查询游客信息
     * 
     * @param partnerId 游客信息主键
     * @return 游客信息
     */
    @Override
    public WuserPartner selectWuserPartnerByPartnerId(Long partnerId)
    {
        return wuserPartnerMapper.selectWuserPartnerByPartnerId(partnerId);
    }

    /**
     * 查询游客信息列表
     * 
     * @param wuserPartner 游客信息
     * @return 游客信息
     */
    @Override
    public List<WuserPartner> selectWuserPartnerList(WuserPartner wuserPartner)
    {
        WuserExt wuserExt = wuserExtMapper.selectWuserExtByUserId(wuserPartner.getUesrId());
        // 在游客信息中更新本人信息
        if (wuserExt != null) {
            refreshSelfPartner(wuserExt);
        }
        return wuserPartnerMapper.selectWuserPartnerList(wuserPartner);
    }

    /**
     * 在游客信息中更新本人信息
     * @param wuserExt 微信用户信息
     */
    private void refreshSelfPartner(WuserExt wuserExt) {
        try {
            WuserPartner wuserPartner = new WuserPartner();
            wuserPartner.setUesrId(wuserExt.getUserId());
            wuserPartner.setIsSelf("1");
            List<WuserPartner> wuserPartners = wuserPartnerMapper.selectWuserPartnerList(wuserPartner);
            if (wuserPartners.size() == 0) {
                // 新增
                wuserPartner.setName(wuserExt.getNickName());
                wuserPartner.setPhone(wuserExt.getPhonenumber());
                wuserPartner.setPhoneAuth(wuserExt.getPhoneAuth());
                wuserPartner.setIdCode(wuserExt.getUserIdcode());
                wuserPartner.setIdCodeAuth(wuserExt.getIdcodeAuth());
                wuserPartner.setFaceAuth(wuserExt.getFaceAuth());
                wuserPartnerMapper.insertWuserPartner(wuserPartner);
            } else {
                boolean b = false;
                wuserPartner = wuserPartners.get(0);
                if (StringUtils.isNotEmpty(wuserExt.getPhonenumber()) && !StringUtils.equals(wuserPartner.getPhone(), wuserExt.getPhonenumber())) {
                    // 手机号不一致时更新手机号
                    wuserPartner.setPhone(wuserExt.getPhonenumber());
                    wuserPartner.setPhoneAuth(wuserExt.getPhoneAuth());
                    b = true;
                }
                if (StringUtils.isNotEmpty(wuserExt.getUserIdcode()) && !StringUtils.equals(wuserPartner.getIdCode(), wuserExt.getUserIdcode())) {
                    // 身份证号不一致时更新身份证
                    wuserPartner.setIdCode(wuserExt.getUserIdcode());
                    wuserPartner.setIdCodeAuth(wuserExt.getIdcodeAuth());
                    b = true;
                }
                // 当手机号和身份证存在不一致时执行更新操作
                if (b) {
                    wuserPartnerMapper.updateWuserPartner(wuserPartner);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 校验游客信息的手机认证、身份认证、人脸认证
     * @param wuserPartnerAddReq
     * @return
     */
    private AjaxResult checkAuth(WuserPartnerAddReq wuserPartnerAddReq) {
        // 判断是否需要验证手机号，根据code是否有值进行判断
        if (StringUtils.isNotEmpty(wuserPartnerAddReq.getPhoneAuthCode())) {
            AjaxResult ajaxResult = sendMessage.checkPhoneCodeAtom(wuserPartnerAddReq.getPhone(), wuserPartnerAddReq.getPhoneAuthCode());
            if (ajaxResult.isError()) {
                return ajaxResult;
            } else {
                // 手机号验证成功，保存认证结果 0认证 1未认证
                wuserPartnerAddReq.setPhoneAuth("0");
            }
        }
        // 判断是否需要验证身份证号码
        if (StringUtils.equals("1", wuserPartnerAddReq.getIdCodeAuthRequire())) {
            IdCardUtil idCardUtil = new IdCardUtil();
            AjaxResult ajaxResult = idCardUtil.IdCardVerification(wuserPartnerAddReq.getIdCode(), wuserPartnerAddReq.getName(), secretId ,secretKey);
            if (ajaxResult.isError()) {
                return ajaxResult;
            } else {
                // 身份证验证成功，保存认证结果 0认证 1未认证
                wuserPartnerAddReq.setIdCodeAuth("0");
            }
        }
        // 判断是否需要验证人脸核验结果，根据eidToken是否有值进行判断
        if (StringUtils.isNotEmpty(wuserPartnerAddReq.getEidToken())) {
            EidUtil eidUtil = new EidUtil();
            AjaxResult eidResult = eidUtil.getEidResultV2(secretId, secretKey, wuserPartnerAddReq.getEidToken());
            if (eidResult.isError()) {
                return eidResult;
            } else {
                // 人脸核验成功，保存认证结果 0认证 1未认证
                wuserPartnerAddReq.setFaceAuth("0");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 新增游客信息
     *
     * @param wuserPartnerAddReq 游客信息
     * @return 结果
     */
    @Override
    public AjaxResult insertWuserPartner(WuserPartnerAddReq wuserPartnerAddReq)
    {
        AjaxResult checkResult = checkAuth(wuserPartnerAddReq);
        if (checkResult.isError()) {
            return checkResult;
        }
        WuserPartner wuserPartner = new WuserPartner();
        BeanUtils.copyBeanProp(wuserPartner, wuserPartnerAddReq);
        wuserPartner.setUesrId(SecurityUtils.getLoginUser().getUserid());
        // 根据前端传入的数据查询游客信息，如已有相同数据不做处理
        List<WuserPartner> wuserPartners = wuserPartnerMapper.selectWuserPartnerList(wuserPartner);
        if (wuserPartners.isEmpty()) {
            int i = wuserPartnerMapper.insertWuserPartner(wuserPartner);
            return i > 0 ? AjaxResult.success() : AjaxResult.error();
        } else {
            WuserPartner updatePartner = wuserPartners.get(0);
            BeanUtils.copyBeanProp(updatePartner, wuserPartner);
            int i = wuserPartnerMapper.updateWuserPartner(updatePartner);
            return i > 0 ? AjaxResult.success() : AjaxResult.error();
        }
    }

    /**
     * 修改游客信息
     * 
     * @param wuserPartnerAddReq 游客信息
     * @return 结果
     */
    @Override
    public AjaxResult updateWuserPartner(WuserPartnerAddReq wuserPartnerAddReq)
    {
        AjaxResult checkResult = checkAuth(wuserPartnerAddReq);
        if (checkResult.isError()) {
            return checkResult;
        }
        WuserPartner wuserPartner = new WuserPartner();
        BeanUtils.copyBeanProp(wuserPartner, wuserPartnerAddReq);
        // 回填个人信息
        if (StringUtils.equals(wuserPartner.getIsSelf(), "1")) {
            WuserExt wuserExt = wuserExtMapper.selectWuserExtByUserId(wuserPartner.getUesrId());
            // 手机号未认证并且为空时回填手机号
            if (StringUtils.equals(wuserExt.getPhoneAuth(), "1") && StringUtils.isEmpty(wuserExt.getPhonenumber())) {
                wuserExt.setPhonenumber(wuserPartner.getPhone());
                wuserExt.setPhoneAuth(wuserPartner.getPhoneAuth());
            }
            // 身份证号未认证并且为空时回填身份证
            if (StringUtils.equals(wuserExt.getIdcodeAuth(), "1") && StringUtils.isEmpty(wuserExt.getUserIdcode())) {
                wuserExt.setUserIdcode(wuserPartner.getIdCode());
                wuserExt.setIdcodeAuth(wuserPartner.getIdCodeAuth());
            }
            wuserExtMapper.updateWuserExt(wuserExt);
        }
        int i = wuserPartnerMapper.updateWuserPartner(wuserPartner);
        return i > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 批量删除游客信息
     * 
     * @param partnerIds 需要删除的游客信息主键
     * @return 结果
     */
    @Override
    public int deleteWuserPartnerByPartnerIds(Long[] partnerIds)
    {
        return wuserPartnerMapper.deleteWuserPartnerByPartnerIds(partnerIds);
    }

    /**
     * 删除游客信息信息
     * 
     * @param partnerId 游客信息主键
     * @return 结果
     */
    @Override
    public int deleteWuserPartnerByPartnerId(Long partnerId)
    {
        return wuserPartnerMapper.deleteWuserPartnerByPartnerId(partnerId);
    }

    /**
     * 获取E证通token
     *  appKey
     *      motion 体育场（运动公园）
     *      island 生态岛
     * @param appKey 小程序应用别名 “生态岛”小程序默认为空，其余需传入对应的标识
     * @return
     */
    @Override
    public AjaxResult getEidToken(String appKey, String idCode, String name) {
        String currMerchantId = merchantId;
        if (StringUtils.equals("motion", appKey)) {
            currMerchantId = motionMerchantId;
        }

        EidUtil eidUtil = new EidUtil();
        return eidUtil.getEidToken(idCode, name, secretId, secretKey, currMerchantId);
    }

    /**
     * 获取E证通结果信息
     *
     * @param eidToken eidToken
     * @param id 游客信息id
     * @return
     */
    @Override
    public AjaxResult getEidResult(String eidToken, Long id) {
        EidUtil eidUtil = new EidUtil();
        AjaxResult eidResultV2 = eidUtil.getEidResultV2(secretId, secretKey, eidToken);
        if (eidResultV2.isSuccess() && null != id) {
            WuserPartner wuserPartner = wuserPartnerMapper.selectWuserPartnerByPartnerId(id);
            wuserPartner.setFaceAuth("0");
            wuserPartnerMapper.updateWuserPartner(wuserPartner);
        }
        return eidResultV2;
    }
}
